import { App } from "vue";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import LoginVue from "../views/Login/index.vue";
import { useUserStore } from "@/store";
import { user } from "@/api";


const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        name: "login",
        // 一般来说，项目的第一个进入的页面不要使用 路由懒加载
        component: LoginVue,
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});


router.beforeEach((to, from, next) => {

    const userStore = useUserStore();
    let token = localStorage.getItem("token");


    if (!token && to.path !== "/login") {
        next("/login");
    }

    else if (token && to.path === "/login") {

        next(from.path);
    }

    else if (
        token &&
        userStore.menus.length === 0 &&
        router.getRoutes().length === 1 &&
        (from.path === "/" || from.path === "/login")
    ) {
        // 登录成功后，需要请求用户的菜单数据
        user.userInfoApi().then((res) => {
            if (res.code === 200) {

                userStore.menus = res.data.menus;
                const menus: IMenu[] = JSON.parse(JSON.stringify(res.data.menus));
                
                const parents: IActiveMenu[] = menus.filter(
                    (menu) => menu.parentId === 0
                );
                menus.forEach((menu) => {
                    
                    const p = parents.find((p) => p.id === menu.parentId);
                    if (p) {
                        if (!p.children) {
                            p.children = [];
                        }
                        p.children.push(menu);
                    }
                });
                userStore.username = res.data.username;
                
                parents.forEach((parent) => {
                    const route: RouteRecordRaw = {
                        
                        path: "/" + parent.name,
                        name: parent.name,

                        component: () => import("../views/Home/index.vue"),
                        children: [],
                        meta: {
                            title: parent.title
                        },
                    };
                    //   然后添加子路由
                    parent.children?.forEach((child) => {
                        route.children.push({
                            // path ===>  /一级/二级
                            path: `/${parent.name}/${child.name}`,
                            name: child.name,
                            component: () =>
                                import(`../views/${parent.name}/${child.name}.vue`),
                                meta: {
                                    title: child.title,
                                }
                        });
                    });

                    router.addRoute(route);
                });

                router.addRoute({
                    path: "/",
                    name: "home",
                    redirect: '/index',
                    component: () => import("../views/Home/index.vue"),
                    children: [
                        {
                            path: "/index",
                            name: "index",
                            component: () => import("../views/index/index.vue"),
                        },
                    ],
                });
                // 你想去哪，就是to.path
                next(to.fullPath)
            }
        });
    } else {
        next();
    }
});

export default (app: App<Element>) => {
    app.use(router);
};

export { router }